package com.secxiot.common.utils;



import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 车辆
 */
@Component
public class CarGpsUtil {
    private static final Logger LOG = LoggerFactory.getLogger(CarGpsUtil.class);
    private final static String APP_ID="西安救护车";
    private final static String APP_SIGNATURE="365d740d60bc93c0ce613cb1e1f53281";
    /**
     * 发送post请求
     *
     * @param url        路径
     * @param jsonObject 参数(json类型)
     * @param encoding   编码格式
     * @return
     * @throws ParseException
     * @throws IOException
     */
    public static String SendPost(String url, JSONObject jsonObject, String encoding) throws IOException {
        String body = "";
        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        StringEntity s = new StringEntity(jsonObject.toString(), "utf-8");
        s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));

        httpPost.setEntity(s);
        //httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
        httpPost.setHeader("Content-type", "application/json");
        httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

        CloseableHttpResponse response = client.execute(httpPost);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            body = EntityUtils.toString(entity, encoding);
        }
        EntityUtils.consume(entity);
        //释放链接
        response.close();
        return body;
    }

    public static JSONObject SendGet(String url, Map<String, String> map) {
        String body = "";
        CloseableHttpClient client = HttpClients.createDefault();
        StringBuilder urlget = new StringBuilder(url);
        String token = "";
        int count = 1;
        if (map == null) {
            return null;
        }
        for (Map.Entry<String, String> entry : map.entrySet()) {
            if (entry.getKey().equals("Ttoken")) {
                token = entry.getValue();
                continue;
            }
            if (count == 1) {
                urlget.append("?").append(entry.getKey()).append("=").append(entry.getValue());
            } else {
                urlget.append("&&").append(entry.getKey()).append("=").append(entry.getValue());
            }
            System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
            count = count + 1;
        }

        HttpGet get = new HttpGet(urlget.toString());
        get.setHeader("Accept", "application/json;charset=utf-8");
        if (token != null && !token.equals("")) {
            get.setHeader("Ttoken", token);
        }

        try {
            HttpResponse httpResponse = client.execute(get);
            HttpEntity entity = httpResponse.getEntity();
            if (entity != null) {
                body = EntityUtils.toString(entity);
            }
            EntityUtils.consume(entity);
            System.out.println("Response:" + "\n" + body);
            //String data = entity.toString();
            /*System.out.println("获取的数据" + data);
            InputStream instreams = entity.getContent();
            String str = ConvertStreamToString(instreams);
            System.out.println("Response:" + "\n" + str);
            JSONObject jsonObject = JSONObject.fromObject(JSON.parseObject(str));*/
            return JSONObject.parseObject(body);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String getAccessToken() throws IOException {
        long time = new Date().getTime();
        JSONObject json = new JSONObject();
        json.put("appid", APP_ID);
        json.put("time", time);
        json.put("signature", APP_SIGNATURE);
        String send = SendPost("http://open.figps.com/api/auth", json, "UTF-8");
        JSONObject jsonObject = JSONObject.parseObject(send);
        String accessToken = jsonObject.getString("accessToken");
        if(StringUtils.isBlank(accessToken)){
            getAccessToken();
        }
        return accessToken;
    }

    public static JSONObject getPosition(String accessToken) throws IOException {
        Map<String, String> map = new HashMap<>();
        map.put("accessToken", accessToken);
        return SendGet("http://open.figps.com/api/device/locations/search-by-organization", map);
    }

    public static void main(String[] args) throws IOException {
        JSONObject json = new JSONObject();
        json.put("appid", "西安救护车");
        json.put("time", "1611225091");
        json.put("signature", "365d740d60bc93c0ce613cb1e1f53281");
        String send = SendPost("http://open.figps.com/api/auth", json, "UTF-8");
        System.out.println(send);
        JSONObject jsonObject1 = JSONObject.parseObject(send);
        LOG.error(send);
        String accessToken = jsonObject1.getString("accessToken");
        Map<String, String> map = new HashMap<>();

        map.put("accessToken", accessToken);
        JSONObject jsonObject = SendGet("http://open.figps.com/api/device/locations/search-by-organization", map);
        System.out.println(jsonObject);
        JSONArray data = jsonObject.getJSONArray("data");
        for(Object obj:data){
            JSONObject jb = (JSONObject) obj;
            LOG.error(jb.getString("imei"));
            LOG.error(jb.getDouble("lat").toString());
            LOG.error(jb.getDouble("lng").toString());
        }
        for(int i=0;i<data.size();i++){
            JSONObject jb = (JSONObject) data.get(i);
            LOG.error(jb.getString("imei"));
            LOG.error(jb.getDouble("lat").toString());
            LOG.error(jb.getDouble("lng").toString());
        }
    }
}
